<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, inject } from 'vue'
import { useProjectStore, Task } from '../stores/store'
import TaskStep from './TaskStep.vue'
import { storeToRefs } from 'pinia'
import Sortable from 'sortablejs'
// 正确注入setTaskBar函数
const setTaskBar = inject('setTaskBar') as ((text: string, progress?: number) => void)
const printToTerm = inject('printToTerm') as ((text: string, lvl?: string) => void)

// 使用store
const projectStore = useProjectStore()

// 从projectStore中解包出动态响应的currentTaskIndex
const { currentTaskIndex, isTaskRunning } = storeToRefs(projectStore)

const taskStepsContainer = ref(null) // 步骤拖动容器
// const currentTaskInstance = ref(null) // 保存当前任务实例

// 在组件挂载时确保currentTaskIndex正确初始化
onMounted(() => {
  // 确保currentTaskIndex在有效范围内
  if (projectStore.settings.tasks && projectStore.settings.tasks.length > 0) {
    if (currentTaskIndex.value === undefined ||
      currentTaskIndex.value < 0 ||
      currentTaskIndex.value >= projectStore.settings.tasks.length) {
      currentTaskIndex.value = 0
    }
  }

  // 初始化任务步骤的拖拽功能
  if (taskStepsContainer.value) {
    Sortable.create(taskStepsContainer.value, {
      animation: 150,
      handle: '.step-cursor-move',
      onEnd: function(evt) {
        const oldIndex = evt.oldIndex
        const newIndex = evt.newIndex

        if (oldIndex !== newIndex && oldIndex !== undefined && newIndex !== undefined) {
          // 重新排序当前任务的步骤
          const task = currentTask.value
          const steps = [...task.steps]
          const movedItem = steps.splice(oldIndex, 1)[0]
          steps.splice(newIndex, 0, movedItem)

          // 更新store中的数据
          projectStore.updateTaskSteps(task.name, steps)
        }
      }
    })
  }
})

// 计算属性：当前任务
const currentTask = computed(() => {
  if (currentTaskIndex.value !== undefined &&
    currentTaskIndex.value >= 0 &&
    currentTaskIndex.value < projectStore.settings.tasks.length) {
    return projectStore.settings.tasks[currentTaskIndex.value]
  }
  // 如果索引无效，返回第一个任务或null
  return projectStore.settings.tasks[0]
})

// 添加新步骤
const addStep = (index: number) => {
  projectStore.addStep(currentTask.value.name, index)
}

// 删除步骤
const deleteStep = (index: number) => {
  const task = currentTask.value
  if (task.steps.length > 1) {
    projectStore.deleteStep(task.name, index)
  } else {
    alert('至少需要保留一个步骤')
  }
}

// 添加新任务
const addTask = () => {
  const newTaskName = prompt('请输入新任务名称:')
  if (newTaskName) {
    const newTask: Task = {
      name: newTaskName,
      count: [],
      timer: [],
      steps: [
        {
          id: projectStore.generateUniqueId(),
          name: '示例步骤1',
          executionCondition: null, // 使用空数组以匹配类型定义
          executionMethods: [{
            action: 'left_click',
            target: ''
          }],
          expectedResult: {
            conditionType: 'none',
            value: ''
          },
          failureHandling: {
            action: 'wait_and_retry',
            value: '1'
          },
          nextStepConditions: []
        }
      ]
    }

    const success = projectStore.addTask(newTask)
    if (success) {
      // 切换到新创建的任务
      currentTaskIndex.value = projectStore.settings.tasks.length - 1
    }
  }
}

// 删除当前任务
const deleteTask = () => {
  if (projectStore.settings.tasks.length <= 1) {
    alert('至少需要保留一个任务')
    return
  }

  const taskName = currentTask.value.name
  const confirmDelete = confirm(`确定要删除任务 "${taskName}" 吗？`)
  if (confirmDelete) {
    const success = projectStore.deleteTask(taskName)
    if (success) {
      // 如果删除的是最后一个任务，调整当前索引
      if (currentTaskIndex.value >= projectStore.settings.tasks.length) {
        currentTaskIndex.value = projectStore.settings.tasks.length - 1
      }
    }
  }
}

// 测试当前任务
const testTask = async () => {
  // 如果任务正在运行，则停止任务
  try {
    if (isTaskRunning.value) {
      await window.pywebview.api.stopTask()
      setTaskBar('正在停止任务...')
      printToTerm('正在停止任务...', 'info')
      isTaskRunning.value = false
      return
    }

    // 设置任务运行状态
    isTaskRunning.value = true

    const taskToTest = JSON.parse(JSON.stringify(currentTask.value))

    // 调用Python端的任务执行功能
    const result = await window.pywebview.api.executeTask(taskToTest)

    if (result.success) {
      setTaskBar('任务执行成功')
      printToTerm('任务执行成功', 'success')
    } else {
      setTaskBar('任务执行失败')
      printToTerm(`任务执行失败: ${result.msg}`, 'error')
    }
  } catch (error) {
    console.error('任务执行过程中出现错误:', error)
    printToTerm(`任务执行过程中出现错误，请查看控制台获取更多信息: ${error}`, 'error')
    setTaskBar('任务执行过程中出现错误')
  } finally {
    // 重置任务运行状态
    isTaskRunning.value = false
  }
}


// 保存任务到settings中
const saveTask = () => {
  const taskToSave = JSON.parse(JSON.stringify(currentTask.value)) as Task
  const existingTaskIndex = projectStore.settings.tasks.findIndex(
    (task) => task.name === taskToSave.name
  )

  if (existingTaskIndex !== -1) {
    // 如果任务已存在，则更新它
    projectStore.updateTask(projectStore.settings.tasks[existingTaskIndex].name, taskToSave)
  } else {
    // 如果任务不存在，则添加新任务
    projectStore.addTask(taskToSave)
  }

  projectStore.saveSettings()
  alert(`任务 "${taskToSave.name}" 已保存成功！`)
}

// 加载JSON
const loadJSON = (event: any) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e: any) => {
      try {
        const data = JSON.parse(e.target.result)
        projectStore.setTasks(data)
        // 重置当前任务索引
        currentTaskIndex.value = 0
      } catch (error) {
        alert('JSON格式错误')
      }
    }
    reader.readAsText(file)
  }
}

/**
 * 额外的条件类型，根据计时器和计数器的数量增加，
 * { label: '计数器1', value: '0' },
 * { label: '计时器1', value: new Date().now() },
 *
 */
const additionalConditionTypes = computed(() => {
  return []
})
</script>

<template>
  <div class="create-task p-4">
    <div class="header mb-4 flex justify-between items-center">
      <h1 class="text-2xl font-bold">创建任务</h1>
      <div>
        <input
          type="file"
          accept=".json"
          @change="loadJSON"
          class="hidden"
          id="json-loader"
        />
        <label
          for="json-loader"
          class="px-4 py-2 bg-blue-500 text-white rounded cursor-pointer mr-2"
        >
          加载任务
        </label>
        <button
          @click="saveTask"
          class="px-4 py-2 bg-green-500 text-white rounded"
        >
          保存任务
        </button>
      </div>
    </div>

    <div class="task-selector mb-4">
      <div class="flex items-center">
        <label class="block font-medium mb-1 mr-2">选择任务:</label>
        <select
          v-model="currentTaskIndex"
          class="p-2 border border-gray-300 rounded mr-2"
        >
          <option
            v-for="(task, index) in projectStore.settings.tasks"
            :key="task.name"
            :value="index"
          >
            {{ task.name }}
          </option>
        </select>
        <button
          @click="addTask"
          class="px-3 py-1 bg-blue-500 text-white rounded mr-2"
        >
          添加任务
        </button>
        <button
          @click="deleteTask"
          class="px-3 py-1 bg-red-500 text-white rounded mr-2"
        >
          删除任务
        </button>
        <button
          @click="testTask"
          :class="isTaskRunning ? 'bg-yellow-500 hover:bg-yellow-600' : 'bg-green-500 hover:bg-green-600'"
          class="px-3 py-1 text-white rounded"
        >
          {{ isTaskRunning ? '停止任务' : '测试任务' }}
        </button>
      </div>
    </div>

    <div class="task-name mb-4">
      <label class="block font-medium mb-1">任务名称:</label>
      <input
        v-model="currentTask.name"
        type="text"
        class="w-full p-2 border border-gray-300 rounded"
        placeholder="输入任务名称"
      />
    </div>

    <div ref="taskStepsContainer" class="task-steps">
      <TaskStep
        v-for="(step, index) in currentTask.steps"
        :key="step.id"
        :step="step"
        :index="index"
        :task-name="currentTask.name"
        :additional-condition-types="additionalConditionTypes"
        @delete="() => deleteStep(index)"
        @add="(stepIndex) => addStep(stepIndex)"
      />
    </div>
  </div>
</template>
